package cn.com.xj.plat.controller;

import cn.com.xj.common.enums.OrderStatus;
import cn.com.xj.common.enums.QuotesStatus;
import cn.com.xj.common.enums.YesOrNo;
import cn.com.xj.common.param.out.ServiceResp;
import cn.com.xj.common.param.valid.ValidUtils;
import cn.com.xj.common.service.aspect.bean.BeanUtil;
import cn.com.xj.plat.evt.QueryDictEvt;
import cn.com.xj.plat.evt.cargo.QueryCargoEvt;
import cn.com.xj.plat.evt.customService.EditCustomServiceEvt;
import cn.com.xj.plat.evt.customService.QueryCustomServiceEvt;
import cn.com.xj.plat.evt.insurer.QueryInsurerEvt;
import cn.com.xj.plat.evt.order.*;
import cn.com.xj.plat.evt.orderQuotes.QueryOrderQuotesEvt;
import cn.com.xj.plat.factory.BaseFactory;
import cn.com.xj.plat.service.*;
import cn.com.xj.plat.util.LoginUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {
    @Autowired
    private DictService dictService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CargoService cargoService;
    @Autowired
    private CustomServService customServService;
    @Autowired
    private InsurerService insurerService;
    @Autowired
    private OrderQuotesService orderQuotesService;

    @RequestMapping("/list")
    public String list(QueryOrderEvt evt,Model model){
        model.addAttribute("queryEvt",evt);
        return "/order/list";
    }

    @RequestMapping("/page")
    public String page(QueryOrderEvt evt, Model model){
        try{
            model.addAttribute("queryEvt",evt);
            if(OrderStatus.SJJUDAN.name().equals(evt.getOrderStatus())){
                evt.setLoadQuotes(YesOrNo.Y.name());
                evt.setQuotesStatus(QuotesStatus.SJJUDAN.name());
            }
            if(OrderStatus.DHZFK.name().equals(evt.getOrderStatus())){
                evt.setLoadQuotes(YesOrNo.Y.name());
                evt.setQuotesStatus(QuotesStatus.SJJIEDAN.name());
            }
            if(evt.getInit()==1){
                ServiceResp<Object> resp = orderService.count(BeanUtil.transBean2Map(evt));
                model.addAttribute("total",resp.getBody());
            }
            ServiceResp<Object> respList = orderService.query(BeanUtil.transBean2Map(evt));
            List<Map<String,Object>> items = (List<Map<String,Object>>)respList.getBody();
            if(items!=null&&items.size()>0){
                for(Map<String,Object> map : items){
                    if(map.get("cargoType")!=null){
                        map.put("cogoTypeCh",
                                loadCargoTypeCh(map.get("cargoType").toString()));
                    }
                }
            }
            model.addAttribute("list",items);
        }catch(Exception e){
            e.printStackTrace();
            return "/common/error";
        }
        return "/order/page";
    }

    private String loadCargoTypeCh(String cargoType){
        if(StringUtils.isBlank(cargoType))return null;
        QueryDictEvt queryDictEvt = new QueryDictEvt();
        queryDictEvt.setTableName("t_cargo_type");
        queryDictEvt.setColumnName("type");
        queryDictEvt.setDictValue(cargoType);
        ServiceResp<Object> auditRemarks = dictService.queryCache(BeanUtil.transBean2Map(queryDictEvt));
        if (auditRemarks.success()) {
            List<Map<String,Object>> dicts = (List<Map<String,Object>>)auditRemarks.getBody();
            String dictDesc = (dicts!=null&&dicts.size()>0)?dicts.get(0).get("dictDesc").toString():"";
            return dictDesc;
        }
        return null;
    }

    @RequestMapping("toAdd")
    public String toAdd(Model model) {
        return "/order/edit";
    }

    @RequestMapping(value = "doAdd",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp doAdd(AddOrderEvt evt, HttpSession session){
        try {
            return BaseFactory.getInstance().add(orderService,evt,session);
        }catch (Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统错误");
        }
    }

    @RequestMapping("/toEdit")
    public String toEdit(QueryOrderEvt evt,
                         Model model){
        try{
            if(evt.getId()==null)return "/common/error";
            BaseFactory.getInstance().toEdit(orderService, BeanUtil.transBean2Map(evt),model);
        }catch(Exception e){
            e.printStackTrace();
            return "/common/error";
        }
        return "/order/edit";
    }

    @RequestMapping(value = "doEdit",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp doEdit(EditOrderEvt evt){
        try {
            return BaseFactory.getInstance().doEdit(orderService,evt);
        }catch (Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统错误");
        }
    }

    @RequestMapping("/toService")
    public String toService(QueryCustomServiceEvt evt,
                           Model model){
        if(StringUtils.isBlank(evt.getOrderNo()))return "/common/error";
        ServiceResp<Object> resp =
                customServService.query(BeanUtil.transBean2Map(evt));
        if(resp.success()){
            List<Map<String,Object>> items = (List<Map<String,Object>>)resp.getBody();
            if(items==null||items.size()==0)return "/common/error";
            model.addAttribute("item",items.get(0));
        }
        return "/order/service";
    }

    @ResponseBody
    @RequestMapping("/doAssign")
    public ServiceResp doAssign(AssignEvt evt){
        try{
            ServiceResp resp = new ValidUtils().validate(evt);
            if(!resp.success())return resp;
            return orderService.assignOrder(BeanUtil.transBean2Map(evt));
        }catch(Exception e){
            e.printStackTrace();
            return new ServiceResp().error("系统异常");
        }
    }

    @RequestMapping("/toAssign")
    public String toAssign(QueryOrderEvt evt,
                           Model model){
        try{
            if(evt.getId()==null)return "/common/error";
            evt.setLoadGoods(YesOrNo.Y.name());
            ServiceResp<Object> resp = orderService.query(BeanUtil.transBean2Map(evt));
            List<Map<String,Object>> items = (List<Map<String,Object>>)resp.getBody();
            Map<String,Object> item = items.size()>0?items.get(0):null;
            if(item.get("cargoType")!=null){
                item.put("cogoTypeCh",
                        loadCargoTypeCh(item.get("cargoType").toString()));
            }
            model.addAttribute("item",item);

            // 获取接单司机列表
            QueryOrderQuotesEvt queryOrderQuotesEvt = new QueryOrderQuotesEvt();
            queryOrderQuotesEvt.setOrderId(evt.getId());
            queryOrderQuotesEvt.setQuotesStatus(QuotesStatus.DSJJIEDAN.name());
            ServiceResp quotesResp =
                    orderQuotesService.queryQuotes(queryOrderQuotesEvt);
            model.addAttribute("quotesItem",quotesResp.getBody());
        }catch(Exception e){
            return "/common/error";
        }
        return "/order/assign";
    }

    @RequestMapping("/toDetail")
    public String toDetail(QueryOrderEvt evt,
                           Model model){
        try{
            if(evt.getId()==null&&StringUtils.isBlank(evt.getOrderNo()))return "/common/error";
            ServiceResp<Object> resp =
                    orderService.query(BeanUtil.transBean2Map(evt));
            if(!resp.success())return "/common/error";
            JSONArray objects = JSONArray.parseArray(JSON.toJSONString(resp.getBody()));
            if(objects!=null&&objects.size()>0){
                JSONObject jsonObject = (JSONObject)objects.get(0);
                jsonObject = setInsurer(jsonObject);
                jsonObject = setCargo(jsonObject);
                if(jsonObject.get("cargoType")!=null){
                    jsonObject.put("cargoTypeCh",
                            loadCargoTypeCh(jsonObject.get("cargoType").toString()));
                }
                model.addAttribute("item",jsonObject);
            }
        }catch(Exception e){
            return "/common/error";
        }
        return "/order/detail";
    }

    private JSONObject setInsurer(JSONObject jsonObject){
        Long insurerId = jsonObject.getLong("insurerId");
        if(insurerId!=null){
            QueryInsurerEvt queryInsurerEvt = new QueryInsurerEvt();
            queryInsurerEvt.setId(insurerId);
            ServiceResp<Object> insurerResp =
                    insurerService.query(BeanUtil.transBean2Map(queryInsurerEvt));
            if(insurerResp.success()){
                JSONArray objects = JSONArray.parseArray(JSON.toJSONString(insurerResp.getBody()));
                if(objects!=null)
                    jsonObject.put("insurer",objects.size()>0?objects.get(0):null);
            }
        }
        return jsonObject;
    }

    private JSONObject setCargo(JSONObject jsonObject){
        Long orderId = jsonObject.getLong("id");
        QueryCargoEvt queryCargoEvt = new QueryCargoEvt();
        queryCargoEvt.setOrderId(orderId);
        ServiceResp<Object> cargoResp =
                cargoService.query(BeanUtil.transBean2Map(queryCargoEvt));
        if(cargoResp.success()){
            jsonObject.put("cargos",cargoResp.getBody());
        }
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/resetOrder", method = RequestMethod.POST)
    public ServiceResp<Object> resetOrder(OrderEvt evt) {
        try {
            return orderService.resetOrder(evt);
        } catch (Exception e) {
            return new ServiceResp<Object>().error("系统错误");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/cancleOrder", method = RequestMethod.POST)
    public ServiceResp<Object> cancleOrder(DelOrderEvt evt) {
        try {
            return orderService.cancleOrder(evt);
        } catch (Exception e) {
            return new ServiceResp<Object>().error("系统错误");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/confirmReceipt", method = RequestMethod.POST)
    public ServiceResp<Object> confirmReceipt(EditOrderEvt evt) {
        try {
            return orderService.confirmReceipt(evt);
        } catch (Exception e) {
            return new ServiceResp<Object>().error("系统错误");
        }
    }

    private String detail(QueryOrderEvt evt,Model model,String page){
        try{
            if(evt.getId()==null)return "/common/error";
            BaseFactory.getInstance().toDetail(orderService,BeanUtil.transBean2Map(evt),model);
        }catch(Exception e){
            return "/common/error";
        }
        return page;
    }

    @ResponseBody
    @RequestMapping(value = "/confirmOrder", method = RequestMethod.POST)
    public ServiceResp<Object> confirmOrder(EditOrderEvt evt) {
        try {
            evt.setOrderStatus(OrderStatus.YSH.name());
            return orderService.edit(BeanUtil.transBean2Map(evt));
        } catch (Exception e) {
            return new ServiceResp<Object>().error("系统错误");
        }
    }

}
